import { HomeComponent } from './../home/home.component';
import { TableDetailComponent } from './../tableDetail/tableDetail.component';
import { NavController, NavParams } from 'ionic-angular';
import { CacheManager } from './../../common/cacheManager';
import { ActivatedRoute } from '@angular/router';
import { StoreService } from './../../service/store.service';
import { UpdateTableStatusMessageHandle } from './../../common/messageHandle/updateTableStatus';
import { ConfirmParams } from './../../component/primeng/confirm/confirm.module';
import { TableCancelSettledMessageHandle } from './../../common/messageHandle/tableCancelSettledMsgHandle';
import { MdDialog, MdSnackBar } from "@angular/material";
import { OrderMessageHandle } from './../../common/messageHandle/orderMsgHandle';
import { TableService } from './../../service/table.service';
import { InnerMessageType, FNCManager } from './../../common/fncManager';
import { MessageHandleManager } from './../../common/messageHandle/msgHandleMg';
import { TableMessageHandle } from './../../common/messageHandle/tableMsgHandle';
import { NavigateService, ViewStatus } from './../../service/navigate.service';
import { Component, ElementRef, ViewChild, QueryList, Input, OnInit, Renderer, trigger, state, style, transition, animate, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { NgClass } from '@angular/common';
import { MessageBoxService, MessageResult, GrowlMessageType } from '../../component/messageBoxService';
import { OpenTableService } from "./view/openTable";
import { loadingMask } from "./../../component/decorators";
import { TablePartyMessageHandle } from './../../common/messageHandle/tablePartyMsgHandle';
import { CompletePayMessagehandle } from "../../common/messageHandle/completePayMsgHandle";
import { ObjectCopier } from "../../common/objectCopier";
import { TableSettledMessageHandle } from "../../common/messageHandle/tableSettledMsgHandle";

declare let EventRegistHandle: any;
@Component({
    //moduleId: module.id,
    selector: 'div[table]',
    templateUrl: './table.component.html',
    styleUrls: ['./table.component.scss']
})

export class TableComponent implements OnDestroy {
    @ViewChild('start') input: ElementRef;

    state = { tableStatus: {} };
    tabTimer = null;
    isShowCtrl = false;//是否显示点击左右滑动的按钮
    tableStatus = [
        { id: 'all', name: "全部", status: "", disable: false },
        { id: 'busy', name: "使用中", status: "opening", disable: false },
        { id: 'free', name: "空闲", status: "free", disable: false },
        { id: "presettled", name: "预结算", status: "presettled", disable: false },
        { id: "cleaning", name: "待清台", status: "cleaning", disable: true }
    ];
    tableList = [];
    tableZoneList = [];
    selectTableZone; //台桌分区列表
    currentTable = <any>{};
    selectedTableStatus = <any>{ id: 'all', name: "全部", status: "" };
    loading: boolean = true;
    zoneHasTables: boolean = false;
    tableViewStatus = <any>{};
    statusTables = false;//当前状态下是否包含台桌
    private tableMsgHandle: TableMessageHandle;
    private tablePartyMsgHandle: TablePartyMessageHandle;
    private orderMsgHandle: OrderMessageHandle;
    private completePayMsghandle: CompletePayMessagehandle;
    private tableSettledMsgHandler: TableSettledMessageHandle;
    private tableCancelSettledMessageHandle: TableCancelSettledMessageHandle;
    private updateTableStatusMessageHandle: UpdateTableStatusMessageHandle;
    private sub;
    private zoneId;
    constructor(
        private tableSvr: TableService,
        private router: NavigateService,
        private renderer: Renderer,
        private elementRef: ElementRef,
        private msgSvr: MessageBoxService,
        private dialog: MdDialog,
        private acRouter: ActivatedRoute,
        public snackBar: MdSnackBar,
        private ref: ChangeDetectorRef,
        private storeSvr: StoreService,
        public navCtrl: NavController,
        private navParams: NavParams
    ) { }

    async onInit() {
        /**
         * 台桌消息处理
         */
        this.tableMsgHandle = MessageHandleManager.Current.GetMessageHanle<TableMessageHandle>("TableMessageHandle");
        this.tableMsgHandle.OnMessage = async (table) => {
            console.log("this.tableMsgHandle.OnMessage", table);
            let tb = await this.tableSvr.GetTableInfo(table.id);
            for (let i = 0; i < this.tableList.length; i++) {
                if (this.tableList[i].id == tb.id) {
                    this.tableList[i] = tb;
                    break;
                }
            }
            this.checkZonetables();
        }

        this.tablePartyMsgHandle = MessageHandleManager.Current.GetMessageHanle<TablePartyMessageHandle>("TablePartyMessageHandle");
        this.tablePartyMsgHandle.OnMessage = async (tableParty) => {
            console.log("this.tablePartyMessageHandle", tableParty);
            if (!tableParty.tableGroupId) {
                //取消并台的tableparty
                if (tableParty.tableId) {
                    let table = await this.tableSvr.GetTableInfo(<any>tableParty.tableId);
                    for (let i = 0; i < this.tableList.length; i++) {
                        if (this.tableList[i].id == table.id) {
                            this.tableList[i] = table;
                            break;
                        }
                    }
                }
                return;
            }
            let tables = await this.tableSvr.GetGroupTables(<any>tableParty.tableGroupId);
            for (let i = 0; i < this.tableList.length; i++) {
                for (let j = 0; j < tables.length; j++) {
                    if (this.tableList[i].id == tables[j].id) {
                        this.tableList[i] = tables[j];
                    }
                }
            }
        }

        this.tableSettledMsgHandler = MessageHandleManager.Current.GetMessageHanle<TableSettledMessageHandle>("TableSettledMessageHandle");
        this.tableSettledMsgHandler.OnMessage = async (tableId) => {
            let tableGroupId = undefined;
            for (let i = 0; i < this.tableList.length; i++) {
                if (this.tableList[i].id == tableId) {
                    if (this.tableList[i].tableParty) {
                        this.tableList[i].tableParty.status = 'presettled';
                    }
                    if (this.tableList[i].tableParty && this.tableList[i].tableParty.tableGroupId) {
                        tableGroupId = this.tableList[i].tableParty.tableGroupId;
                    }
                    break;
                }
            }
            if (tableGroupId) {
                this.tableList.forEach((table) => {
                    if (table.tableParty && table.tableParty.tableGroupId && table.tableParty.tableGroupId == tableGroupId) {
                        table.tableParty.status = 'presettled';
                    }
                })
            }
            this.checkZonetables();
        }

        this.tableCancelSettledMessageHandle = MessageHandleManager.Current.GetMessageHanle<TableCancelSettledMessageHandle>("TableCancelSettledMessageHandle");
        this.tableCancelSettledMessageHandle.OnMessage = async (tableId) => {
            let tableGroupId = undefined;
            for (let i = 0; i < this.tableList.length; i++) {
                if (this.tableList[i].id == tableId) {
                    if (this.tableList[i].tableParty) {
                        this.tableList[i].tableParty.status = 'opening';
                        if (this.tableList[i].tableParty.tableGroupId) {
                            tableGroupId = this.tableList[i].tableParty.tableGroupId;
                        }
                    }
                    break;
                }
            }
            if (tableGroupId) {
                for (let i = 0; i < this.tableList.length; i++) {
                    if (this.tableList[i].tableParty && this.tableList[i].tableParty.tableGroupId == tableGroupId) {
                        this.tableList[i].tableParty.status = 'opening';
                    }
                }
            }
            this.checkZonetables();
        }
        this.orderMsgHandle = MessageHandleManager.Current.GetMessageHanle<OrderMessageHandle>("OrderMessageHandle");
        this.orderMsgHandle.OnMessage = (order) => {
            console.log("this.orderMessageHandle", order);
            let tb = this.tableList.find(x => x.id == order.extended.table.id);
            if (tb) {
                tb.masterOrder = order;
            }
        }
        /**
         * 订单结算消息
         */
        this.completePayMsghandle = MessageHandleManager.Current.GetMessageHanle<CompletePayMessagehandle>("CompletePayMessagehandle");
        this.completePayMsghandle.OnMessage = async (tableId) => {
            console.log("this.completePayMsghandle", tableId);
            if (tableId) {
                let tb = await this.tableSvr.GetTableInfo((<any>tableId).id);
                for (let i = 0; i < this.tableList.length; i++) {
                    if (this.tableList[i].id == tb.id) {
                        this.tableList[i] = tb;
                    }
                }
            }
        }

        /**
         * 台桌状态更新消息
         */
        this.updateTableStatusMessageHandle = MessageHandleManager.Current.GetMessageHanle<UpdateTableStatusMessageHandle>("UpdateTableStatusMessageHandle");
        this.updateTableStatusMessageHandle.OnMessage = (updateInfo) => {
            console.log(updateInfo);
            if (updateInfo.tableIds && updateInfo.tableIds.length) {
                for (let tableId of updateInfo.tableIds) {
                    for (let i = 0; i < this.tableList.length; i++) {
                        if (this.tableList[i].id == tableId) {
                            this.tableList[i].status = updateInfo.status;
                            if (updateInfo.status == 'cleaning') {
                                delete this.tableList[i].tableParty;
                            }
                        }
                    }
                }
            }
            this.checkZonetables();
        }
    }

    async ionViewDidLoad() {
        await this.getAllTables();
        this.tableSvr.GetTableZoneList().then(data => {
            if (data) {
                this.tableZoneList = data;
            }
            let tableZoneAll = { id: "", name: "所有" };
            this.tableZoneList.push(tableZoneAll);
            this.tableZoneList[0].active = true;
            this.selectTableZone = this.tableZoneList[0];
            this.onSelectTableZone(this.selectTableZone);
            let table = this.tableList.find((t) => {
                return t.zone.id == this.selectTableZone.id;
            });
            if (table) {
                this.zoneHasTables = true;
            }
        });

        await this.getIsCleanTable();
    }

    ionViewWillEnter() {
        this.router.registGoBack(this.navGoBack.bind(this));
        this.onInit();
        this.updateTables();
    }

    async getAllTables() {
        this.loading = true;
        let list = await this.tableSvr.GetTableList({ tableZoneId: "" });
        this.tableList = list;
        this.loading = false;
    }
    /**
     * 更新台桌的状态
     */
    updateTables() {
        this.tableSvr.GetTableList({ tableZoneId: "" }).then((tables) => {
            this.tableList = tables;
        });
    }

    async getTableZoneList() {
        let list = [];
        list = CacheManager.Current.get("tableZoneList");
        if (!list || !list.length) {
            list = await this.tableSvr.GetTableZoneList();
            CacheManager.Current.add({ key: "tableZoneList", value: list });
        }
    }

    async getIsCleanTable() {
        let key = "pos.table.manualCleanTable";
        let config = await this.storeSvr.getStoreConfigs(key);
        if (config) {
            for (let i = 0; i < this.tableStatus.length; i++) {
                if (this.tableStatus[i].id == 'cleaning') {
                    this.tableStatus[i].disable = !config.enable;
                    break;
                }
            }
        }
        this.tableStatus = this.tableStatus.filter((status) => {
            return !status.disable;
        })
    }

    /**
     * 点击台桌分类
     */
    onSelectTableZone(tableZone) {
        if ((this.selectTableZone && tableZone.id == this.selectTableZone.id) || this.loading) {
            return;
        }
        for (let zone of this.tableZoneList) {
            delete zone.active;
        }
        tableZone.active = true;
        this.selectTableZone = tableZone;
        let queryParams: TableQueryParmas = { tableZoneId: tableZone.id };
        if (tableZone.id === "") {
            if (!this.tableList || !this.tableList.length) {
                this.zoneHasTables = false;
            } else {
                this.zoneHasTables = true;
            }
        } else {
            let table = this.tableList.find((t) => {
                return t.zone.id == tableZone.id;
            });
            if (table) {
                this.zoneHasTables = true;
            } else {
                this.zoneHasTables = false;
            }
        }
        this.checkZonetables();
        // this.getTableList(queryParams);
    }

    onSwitchTableStatus(tabStatus, end) {
        // let queryParams: TableQueryParmas = { tableZoneId: this.selectTableZone.id, tableStatus: tabStatus.status };
        // this.getTableList(queryParams);
        if (this.selectTableZone.id === "") {
            if (!this.tableList || !this.tableList.length) {
                this.zoneHasTables = false;
            } else {
                this.zoneHasTables = true;
            }
        } else {
            let table = this.tableList.find((t) => {
                return t.zone.id == this.selectTableZone.id;
            });
            if (table) {
                this.zoneHasTables = true;
            } else {
                this.zoneHasTables = false;
            }
        }
        this.checkZonetables(tabStatus);
        this.selectedTableStatus = tabStatus;
        end.close();
    }

    async onTableClick(table) {
        try {
            this.currentTable = table;
            if (table.status == "opening") {
                // this.router.navigate(["table/item", table.id, this.selectTableZone.id], {
                //     key: "table",
                //     viewStatus: { selectZone: ObjectCopier.Copy(this.selectTableZone) }
                // });
                this.navCtrl.push(TableDetailComponent, {
                    tableId: table.id,
                    zoneId: this.selectTableZone.id
                }, { animate: false })
            } else if (table.status == "cleaning") {
                // let confirmParams: ConfirmParams = {
                //     title: '清台确认',
                //     content: "确认清理台桌【" + table.name + "】？"
                // }
                // let msg = await MessageBoxService.Current.Show(this.dialog, confirmParams);
                // if (msg == MessageResult.Ok) {
                //     let response = await this.tableSvr.finishCleanTable(table.id);
                //     if (response) {
                //         this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "清台成功！");
                //         let thisTable = await this.tableSvr.GetTableInfo(table.id);
                //         for (let i = 0; i < this.tableList.length; i++) {
                //             if (this.tableList[i].id == thisTable.id) {
                //                 this.tableList[i] = thisTable
                //             }
                //         }
                //         FNCManager.Current.InnerMessageNotify(InnerMessageType.TableStatusMsg, { tableIds: [table.id], status: "" });
                //     }
                // }
                this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "店员宝不支持清台操作");
            } else {
                let result = await OpenTableService.Current.open(this.dialog, this.currentTable);
                if (result) {
                    this.onOpenTable(result);
                }
            }
        } catch (error) {
            console.log(error);
        }
    }

    goBack() {
        // return this.router.navigate(["home"]);
        this.navCtrl.setRoot(HomeComponent);
    }

    /**
     * 开台操作
     */
    @loadingMask()
    async onOpenTable(personCount) {
        try {
            let r = await this.tableSvr.OpenTable(this.currentTable.id, personCount);
            //发送开台消息
            FNCManager.Current.InnerMessageNotify(InnerMessageType.DeskTableMsg, r.table);
            FNCManager.Current.InnerMessageNotify(InnerMessageType.OrderMsg, r.masterOrder);
            FNCManager.Current.InnerMessageNotify(InnerMessageType.TablePartyMsg, r.tableParty);

            // this.router.navigate(['order', this.currentTable.id, this.selectTableZone.id], {
            //     key: "table",
            //     viewStatus: { selectZone: ObjectCopier.Copy(this.selectTableZone) }
            // });
            this.navCtrl.push(TableDetailComponent, {
                tableId: this.currentTable.id,
                zoneId: this.selectTableZone.id
            }, { animate: false });
        }
        catch (err) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, err ? err : "开台失败");
        }
    }

    // @loadingMask()
    private async getTableList(queryParams: TableQueryParmas) {
        this.loading = true;
        let list = await this.tableSvr.GetTableList(queryParams);
        // let list = this.getTablesByParams(queryParams);
        if (list && list.length) {
            this.zoneHasTables = true;
        } else {
            this.zoneHasTables = false;
        }
        //根据台桌状态筛选台桌
        if (Array.isArray(list) && queryParams.tableStatus) {
            let result = [];
            if (queryParams.tableStatus == "opening") {
                result = list.filter(item => {
                    return item.status == "opening";
                });
            } else {
                result = list.filter(item => {
                    return item.status != "opening";
                });
            }
            this.tableList = result;
        } else {
            this.tableList = list;
        }
        this.checkZonetables();
        this.loading = false;
    }

    /**
     * 通过查询参数获取台桌
     * @param queryParams 
     */
    // getTablesByParams(queryParams: TableQueryParmas) {
    //     let result = [];
    //     if (queryParams.tableZoneId == "") {
    //         result = this.allTables;
    //     } else if (queryParams.tableZoneId) {
    //         let list = this.allTables.filter((table) => {
    //             return table.zone.id == queryParams.tableZoneId;
    //         });
    //         result = list;
    //     }
    //     return result;
    // }

    checkZonetables(statusObjOri?) {
        let statusObj = undefined;
        if (statusObjOri) {
            statusObj = statusObjOri;
        } else {
            statusObj = this.selectedTableStatus;
        }
        if (statusObj.id == "all") {
            return this.statusTables = false;
        }
        let zoneTables = [];
        if (this.selectTableZone.id == "") {
            zoneTables = this.tableList;
        } else {
            zoneTables = this.tableList.filter((table) => {
                return table.zone.id == this.selectTableZone.id;
            });
        }

        if (!zoneTables || !zoneTables.length) {
            return this.statusTables = false;
        }

        let status = statusObj.status == 'free' ? '' : statusObj.status;
        let result = zoneTables.find((table) => {
            if (statusObj.status == "presettled") {
                let flag = table && table.tableParty && table.tableParty.status == "presettled";
                return flag;
            } else {
                if (!status || status == 'closed') {
                    return !table.status || table.status == "closed";
                }
                return table.status == status;
            }
        });
        if (result) {
            this.statusTables = false;
        } else {
            this.statusTables = true;
        }
    }

    /**
     * 检测台桌状态是否和筛选的状态一致
     * @param tableStatus 当前台桌状态
     */
    checkTableStatus(tableStatus, table?) {
        if (this.selectedTableStatus.status == 'all') {
            return true;
        }
        if (this.selectedTableStatus.status == "free") {
            if (!tableStatus || tableStatus == "" || tableStatus == "closed") {
                return true
            } else {
                return false;
            }
        }
        if (this.selectedTableStatus.status == "opening") {
            if (tableStatus && tableStatus == "opening") {
                return true;
            } else {
                return false;
            }
        }
        if (this.selectedTableStatus.status == "presettled") {
            if (table && table.tableParty && table.tableParty.status == "presettled") {
                return true;
            } else {
                return false;
            }
        }
        if (this.selectedTableStatus.status == "cleaning") {
            if (table && table.status == "cleaning") {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    isShowTable(table) {
        if (!this.selectTableZone || this.selectTableZone.id === "") {
            return true;
        }
        if (table.zone.id != this.selectTableZone.id) {
            return false;
        }
        return true;
    }

    navGoBack() {
        let backBtn = document.getElementById("table-back-btn");
        if (backBtn) {
            this.dialog.closeAll();
            backBtn.click();
        }
    }
    ngOnDestroy() {
        this.router.onPageLoad = null;
        if (this.sub) {
            this.sub.unsubscribe();
        }
    }

    trackByTable(index, table) {
        return table ? table.id : undefined;
    }
}

interface TableQueryParmas {
    tableZoneId?: string;
    tableStatus?: string;
}